from django.shortcuts import render

# Create your views here.
from rest_framework import request
from rest_framework.response import Response

from users.models import User

"""
一。确定需求
二，采用那种请求方式
三。实现
1.前端发送一个ajax请求，给后端，参数是用户名
2.后端接收用户名
3.查询校验是否重复
4.返回响应

GET /users/usernames/(?P<username>\w{5,20})/count/
"""

from rest_framework.views import APIView
"""
1.前端发送的数据，已经在url中校验过了
2.所以不用设计序列器
"""
class RegisterUsernameCountAPIView(APIView):
    """
    获取用户名的个数
    GET:  /users/usernames/(?P<username>\w{5,20})/count/
    """

    def get(self,request,username):

        #通过模型查询,获取用户名个数
        count = User.objects.filter(username=username).count()
        #组织数据
        context = {
            'count':count,
            'username':username
        }
        return Response(context)

class RegisterPhoneCountAPIView(APIView):
    """
    查询手机号的个数
    GET: /users/phones/(?P<mobile>1[345789]\d{9})/count/
    """

    def get(self, request, mobile):
        # 通过模型查询获取手机号个数
        count = User.objects.filter(mobile=mobile).count()
        # 组织数据
        context = {
            'count': count,
            'phone': mobile
        }

        return Response(context)


"""
前端应该将六个参数给我们（username，password,password2,mobile,sms_code,allow）传给后端

1.接收数据
2.校验数据
3.数据入库
4.返回响应
我们可以zhiie用CreateModelMixin,为了学习还是使用APIView
"""
from rest_framework.generics import CreateAPIView
from rest_framework.mixins import CreateModelMixin
from .serializers import RegisterCreateUserSerializer
class RegisterCreateUserView(APIView):

    def post(self):
        # 1.接收数据
        data = request.data
        # 2.校验数据
        serializer = RegisterCreateUserSerializer(data)
        # 校验数据是否正确
        serializer.is_valid(raise_exception=True)
        # 3.数据入库
        serializer.save()
        # 4.返回响应
        return Response(serializer.data)









